package com.tzbank.face.service.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tzbank.face.dao.FaceMapper;
import com.tzbank.face.entity.FaceFlowRecord;
import com.tzbank.face.entity.FaceModel;
import com.tzbank.face.entity.Metainfo;
import com.tzbank.face.service.FaceService;
import com.tzbank.face.utils.AppUtils;
import com.tzbank.redis.RedisUtils;
import com.tzbank.utils.CodeUtil;
import com.tzbank.utils.ResultUtil;

import cn.com.antcloud.api.product.AntCloudProdClient;
import cn.com.antcloud.api.zolozfaceverify.v1_0.request.FaceInitializeRequest;
import cn.com.antcloud.api.zolozfaceverify.v1_0.request.FaceQueryRequest;
import cn.com.antcloud.api.zolozfaceverify.v1_0.response.FaceInitializeResponse;
import cn.com.antcloud.api.zolozfaceverify.v1_0.response.FaceQueryResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
@Service(value = "faceService")
public class FaceServiceImpl implements FaceService {

	@Autowired
	private FaceMapper faceMapper;

	private String ACCESS_KEY = "";
	private String ACCESS_SECRET = "";
	private String ENDPOINT = "";
	private String PRODUCT_INSTANCE_ID = "";

	/**
	 * 建立连接
	 * 
	 * @return
	 */
	public void getFaceConfig() {

		ACCESS_KEY = RedisUtils.getValue("FACE_ACCESS_KEY");
		ACCESS_SECRET = RedisUtils.getValue("FACE_ACCESS_SECRET");
		ENDPOINT = RedisUtils.getValue("FACE_ENDPOINT");
		PRODUCT_INSTANCE_ID = RedisUtils.getValue("FACE_PRODUCT_INSTANCE_ID");
	}

	/**
	 * 人脸初始化认证
	 * 
	 */
	@Transactional
	public Map<String, Object> intoFaceService(FaceModel vo) {
		// 获取配置参数
		getFaceConfig();
		log.info("---------->刷脸服务初始化----->begin");
		// 接入方请求的唯一标识
		String bizId = AppUtils.getbizId();
		// 提取所需的业务参数
		Map<String, String> identityParam = new HashMap<String, String>();
		identityParam.put("identityType", "CERT");// 保持不变
		identityParam.put("certType", "IDCARD");// 保持不变
		// 有身份信息，直接赋值
		identityParam.put("certNo", vo.getCertNo());// 用户身份证号
		identityParam.put("certName", vo.getCertName());// 用户姓名
		Metainfo metainfo = vo.getMetainfo();
		// 将Metainfo对象转化为所需的Json字符串。
		JSONObject metainfoStr = JSONObject.fromObject(metainfo);

		// 通过SDK中建立刷脸初始化请求。
		FaceInitializeRequest initializeRequest = new FaceInitializeRequest(PRODUCT_INSTANCE_ID);
		initializeRequest.setBizId(bizId);
		initializeRequest.setIdentityParam(AppUtils.toRSA(identityParam)); // 加密用户信息
		initializeRequest.setMetainfo(metainfoStr.toString().trim());
		initializeRequest.setExternParam("");

		/* 操作流水记录 */
		FaceFlowRecord faceFlowRecord = new FaceFlowRecord();
		faceFlowRecord.setOperatingUser(vo.getUserId());// 操作用户'
		faceFlowRecord.setRequesSource(vo.getRequestSource());// 请求来源
		faceFlowRecord.setCorrespondingInterface("人脸初始化");// 对应接口
		faceFlowRecord.setRequestParameters(vo.toString());// 请求参数
		faceFlowRecord.setConsumerSeqNo(vo.getConsumerSeqNo());
		//20180628//新加
		faceFlowRecord.setAddress(vo.getAddress());//地址
		faceFlowRecord.setBusinessScenario(vo.getBusinessScenario());//业务场景
		//20180628//结束
		
		
		// 执行刷脸初始化接口
		FaceInitializeResponse response = null;
		String code = "";
		String msg = "";
		// 获取返回信息
		Map<String, String> result = new HashMap<String, String>();
		try {
			// 建立连接
			AntCloudProdClient antCloudClient = AntCloudProdClient.newBuilder().setEndpoint(ENDPOINT)
					.setAccess(ACCESS_KEY, ACCESS_SECRET).build();
			response = antCloudClient.execute(initializeRequest);
			if (response != null && response.isSuccess()) {
				// 成功逻辑
				log.info("-----------刷脸服务初始化成功！！-----------");
				code = CodeUtil.CODE_200.getCode();
				msg = CodeUtil.CODE_200.getName() + "--" + response.getResultMsgSub();
				result.put("ZimId", response.getZimId());
				result.put("BizId", bizId);// 唯一标识
			} else {
				// 错误逻辑
				code = CodeUtil.CODE_500.getCode();
				msg = CodeUtil.CODE_500.getName() + "--" + response.getResultMsgSub();
				log.info("-----------初始化失败，信息有误-----------",msg);
			}

			faceFlowRecord.setResponseResult(
					"[" + msg + "---" + code + "---" + JSONObject.fromObject(result).toString() + "]");// 返回结果
			insertRecord(faceFlowRecord);
		} catch (Exception e) {
			faceFlowRecord.setResponseResult("[人脸初始化认证失败~---500]");// 返回结果
			insertRecord(faceFlowRecord);
			log.info("---------->刷脸服务初始化----->异常报错---->end>",e);
			return ResultUtil.resultMap("刷脸服务初始化失败~"+e.getMessage(), "500", null);
		}
		log.info("---------->刷脸服务初始化---成功运行-->end");
		return ResultUtil.resultMap(msg, code, JSONObject.fromObject(result).toString());
	}

	/**
	 * 刷脸查询认证
	 * 
	 */
	@Transactional
	public Map<String, Object> queryFaceService(FaceModel vo) {
		// 获取配置参数
		getFaceConfig();
		log.info("---------->刷脸服务认证查询----->begin");
		// 操作流水记录
		FaceFlowRecord faceFlowRecord = new FaceFlowRecord();
		faceFlowRecord.setOperatingUser(vo.getUserId());// 操作用户'
		faceFlowRecord.setRequesSource(vo.getRequestSource());// 请求来源
		faceFlowRecord.setCorrespondingInterface("刷脸查询认证");// 对应接口
		faceFlowRecord.setRequestParameters(vo.toString());// 请求参数
		faceFlowRecord.setConsumerSeqNo(vo.getConsumerSeqNo());//
		//20180628//新加
		faceFlowRecord.setAddress(vo.getAddress());//地址
		faceFlowRecord.setBusinessScenario(vo.getBusinessScenario());//业务场景
		//20180628//结束
		
		// 通过SDK中建立刷脸认证查询请求。
		FaceQueryRequest queryRequest = new FaceQueryRequest(PRODUCT_INSTANCE_ID);
		queryRequest.setBizId(vo.getBizId());// 与初始化接口保持一致
		queryRequest.setZimId(vo.getZimId());
		// 执行刷脸认证查询接口
		FaceQueryResponse response = null;
		String code = "";
		String msg = "";
		try {
			// 建立连接
			AntCloudProdClient antCloudClient = AntCloudProdClient.newBuilder().setEndpoint(ENDPOINT)
					.setAccess(ACCESS_KEY, ACCESS_SECRET).build();
			response = antCloudClient.execute(queryRequest);
			if (response != null && response.isSuccess()) {
				// 成功逻辑
				log.info("-----------刷脸服务认证查询成功！！-----------");
				code = CodeUtil.CODE_200.getCode();
				msg = CodeUtil.CODE_200.getName() + "--" + response.getResultMsgSub();
			} else {
				// 错误逻辑
				code = CodeUtil.CODE_500.getCode();
				msg = CodeUtil.CODE_500.getName() + "--" + response.getResultMsgSub();
				log.info("-----------刷脸服务认证查询失败！！-----------",msg);
			}
			/* 操作流水记录 */
			faceFlowRecord.setResponseResult("[" + msg + "---" + code + "]");// 返回结果
			insertRecord(faceFlowRecord);

		} catch (Exception e) {
			/* 操作流水记录 */
			faceFlowRecord.setResponseResult("[刷脸服务认证查询失败~---500]");// 返回结果
			insertRecord(faceFlowRecord);
			log.info("---------->刷脸服务认证查询-----异常报错----->end>",e);
			return ResultUtil.resultMap("刷脸服务认证查询失败！！！~", "500", null);
		}
		log.info("---------->刷脸服务认证查询---成功运行--->end");
		return ResultUtil.resultMap(msg, code, null);
	}

	/**
	 * 插入记录
	 * 
	 */
	public void insertRecord(FaceFlowRecord faceFlowRecord) {

		Calendar cal = Calendar.getInstance();
		faceFlowRecord.setYear(String.valueOf(cal.get(Calendar.YEAR)));
		faceFlowRecord.setMonth(String.valueOf(cal.get(Calendar.MONTH) + 1));
		faceMapper.intoFaceLog(faceFlowRecord);
	}

}
